/**
* JEditor
* the javascript web editor
* project:http://jeditor.googlecode.com
* version:1.2 beta
* author: wjmboss
* email:wjmboss@gmail.com
* msn:wjmboss@msn.com
*/

var $ID = function(_id){
	return document.getElementById(_id);
}

if(typeof(trim) == 'undefined'){
	trim =function(str) {
		return str.replace(/^\s*|\s*$/g,"");
	}
}

var JUtil = {
	addEvent:function(target,evtName,func){
		if(document.addEventListener){
			target.addEventListener(evtName, func, true);
		} else if(document.attachEvent){
			target.attachEvent('on' + evtName, func);
		}
	}
}

function JEditorLoad(){
	var len = JEditor.JEditorHolder.length;

	var fromHandle = function(evt){
		evt = evt ? evt: ( window.event ? window.event :null );
		if(evt == null) return;

		var form = evt.srcElement;

		if(form.tagName.toLowerCase() == 'form'){

			for(var i = 0 ; i < JEditor.JEditorHolder.length; i++){
				var editor = JEditor.JEditorHolder[i];
				if(form == editor.target.form){
					editor.target.value = editor.getValue();
				}
			}
		}
		
	}

	for(var i=0;i<len;i++){
		var ed = JEditor.JEditorHolder[i];
		if(!ed.onload) continue;
		ed.initial();
	}
	JUtil.addEvent(document,'click',editorClosePopup);
}



function HtmlEncode(str) {
	var s = "";

	if (str.length == 0) return ""; 

	s = str.replace(/&/g,"&gt;");
	s = s.replace(/</g,"&lt;");
	s = s.replace(/>/g,"&gt;");
	s = s.replace(/ /g,"&nbsp;");
	s = s.replace(/\'/g,"&#39;");
	s = s.replace(/\"/g,"&quot;");
	s = s.replace(/\n/g,"<br>");

	return s;
}


function HtmlDecode(str) {   
	var s = "";
	if(str.length == 0) return "";

	s = str.replace(/&gt;/g,"&");
	s = s.replace(/&lt;/g,"<");
	s = s.replace(/&gt;/g,">");
	s = s.replace(/&nbsp;/g," ");
	s = s.replace(/&#39;/g,"\'");
	s = s.replace(/&quot;/g,"\"");
	s = s.replace(/<br>/g,"\n");

	return s;
}


function editorClosePopup(evt){
	var len = JEditor.JEditorHolder.length;
	for(var i=0;i<len;i++){
		var ed = JEditor.JEditorHolder[i];
		if(ed.loaded){
			ed.closePopup(evt);
		}
	}
}

JUtil.addEvent(window,'load',JEditorLoad);


if(typeof HTMLElement!="undefined" && !HTMLElement.prototype.insertAdjacentElement){
	HTMLElement.prototype.insertAdjacentElement = function (where,parsedNode) {
	  switch (where){
		case 'beforeBegin':
			this.parentNode.insertBefore(parsedNode,this);
			break;
		case 'afterBegin':
			this.insertBefore(parsedNode,this.firstChild);
			break;
		case 'beforeEnd':
			this.appendChild(parsedNode);
			break;
		case 'afterEnd':
			if (this.nextSibling) {
				this.parentNode.insertBefore(parsedNode,this.nextSibling);
			}
			else {
				this.parentNode.appendChild(parsedNode);
			}
			break;
	  }
	};
	HTMLElement.prototype.insertAdjacentHTML = function (where,htmlStr) {
		var r = this.ownerDocument.createRange();
		r.setStartBefore(this);
		var parsedHTML = r.createContextualFragment(htmlStr);
		this.insertAdjacentElement(where,parsedHTML);
	};
	HTMLElement.prototype.insertAdjacentText = function (where,txtStr) {
		var parsedText = document.createTextNode(txtStr);
		this.insertAdjacentElement(where,parsedText);
	};
}

if(window.Event){
    Event.prototype.__defineSetter__("returnValue",function(b){// 
        if(!b)this.preventDefault();
        return b;
        });
    Event.prototype.__defineSetter__("cancelBubble",function(b){// 设置或者检索当前事件句柄的层次冒泡
        if(b)this.stopPropagation();
        return b;
        });
    Event.prototype.__defineGetter__("srcElement",function(){
        var node=this.target;
        while(node.nodeType!=1)node=node.parentNode;
        return node;
        });
    Event.prototype.__defineGetter__("fromElement",function(){// 返回鼠标移出的源节点
        var node;
        if(this.type=="mouseover")
            node=this.relatedTarget;
        else if(this.type=="mouseout")
            node=this.target;
        if(!node)return;
        while(node.nodeType!=1)node=node.parentNode;
        return node;
        });
    Event.prototype.__defineGetter__("toElement",function(){// 返回鼠标移入的源节点
        var node;
        if(this.type=="mouseout")
            node=this.relatedTarget;
        else if(this.type=="mouseover")
            node=this.target;
        if(!node)return;
        while(node.nodeType!=1)node=node.parentNode;
        return node;
        });
    Event.prototype.__defineGetter__("offsetX",function(){
        return this.layerX;
        });
    Event.prototype.__defineGetter__("offsetY",function(){
        return this.layerY;
        });
} 


var JEditor = function(targetId,width,height){
	this.targetId = targetId;
	this.width = width;
	this.height = height;
	this.index = JEditor.JEditorHolder.length;
	this.popupWin = null;
	this.loaded = false;
	this.iframe = null;
	this.selection = null;
	this.range = null;
	this.value = null;
	this.ubb = false;
	this.status = false;//状态
	this.onload = true;//当window onload时加载jeditor

	JEditor.JEditorHolder.push(this);

	this.editor = null;
	this.frameDocument = null;

	this.toolbarList = new Array();

	this.toolbarList.push({
		tagName:"a",
		className:'separator',
		onClick:function(evt,editor){
		}

	});

	this.toolbarList.push({
		name:'Bold',
		tagName:"a",
		className:'bold',
		value:'',
		title:'加粗',
		onClick:function(evt,editor){
			editor.execCommand('Bold');
		}
	});

	this.toolbarList.push({
		name:'Italic',
		tagName:"a",
		className:'italic',
		value:'',
		title:'斜体',
		onClick:function(evt,editor){
			editor.execCommand('Italic');
		}
	});

	this.toolbarList.push({
		name:'Underline',
		tagName:"a",
		className:'underline',
		value:'',
		title:'下划线',
		onClick:function(evt,editor){
			editor.execCommand('Underline');
		}
	});

	this.toolbarList.push({
		name:'Justifyleft',
		tagName:"a",
		className:'justifyleft',
		value:'',
		title:'居左',
		onClick:function(evt,editor){
			editor.execCommand('Justifyleft');
		}
	});

	this.toolbarList.push({
		name:'Justifycenter',
		tagName:"a",
		className:'justifycenter',
		value:'',
		title:'居中',
		onClick:function(evt,editor){
			editor.execCommand('Justifycenter');
		}
	});

	this.toolbarList.push({
		name:'Justifyright',
		tagName:"a",
		className:'justifyright',
		value:'',
		title:'居右',
		onClick:function(evt,editor){
			editor.execCommand('Justifyright');
		}
	});

	this.toolbarList.push({
		name:'InsertUnorderedList',
		width:100,
		tagName:"a",
		className:'unorderedlist',
		value:'',
		title:'无序列表',
		onClick:function(evt,editor){
			editor.execCommand('InsertUnorderedList');
		}
	});

	this.toolbarList.push({
		name:'InsertOrderedList',
		tagName:"a",
		className:'orderedlist',
		value:'',
		title:'有序列表',
		onClick:function(evt,editor){
			editor.execCommand('InsertOrderedList');
		}
	});

	this.toolbarList.push({
		name:'Outdent',
		tagName:"a",
		className:'outdent',
		value:'',
		title:'减少缩进',
		onClick:function(evt,editor){
			editor.execCommand('Outdent');
		}
	});

	this.toolbarList.push({
		name:'Indent',
		width:100,
		tagName:"a",
		className:'indent',
		value:'',
		title:'增加缩进',
		onClick:function(evt,editor){
			editor.execCommand('Indent');
		}
	});

	this.toolbarList.push({
		name:'Image',
		tagName:"a",
		className:'image',
		value:'',
		title:'插入图片',
		onClick:function(evt,editor){
			evt = evt ? evt: ( window.event ? window.event :null );
			var iframeId = editor.getIframe().name;
			var index = editor.index;

			var html = '<div class="insertImage"><form action="upload.php" method="Post" enctype="multipart/form-data" target="' + iframeId + '"><input type="hidden" name="index" value="' + index + '" /><div class="gear"><a href="" id="_JEditorImageRemote" class="focus" onclick="return JEditor.ImageSelect(this);">远程图片</a><a href="" id="_JEditorImageLocal" onclick="return JEditor.ImageSelect(this);">本地上传</a></div><div id="JEditorImageLocal" style="display:none">选择图片:<br /><input id="JEditorImageLocalURL" type="file" name="img" class="file" /></div><div id="JEditorImageRemote">远程路径:<br /><input type="text" id="JEditorImageRemoteURL" value="http://" /></div><input id="JEditorImageSubmit" type="button" value="确定" /></form></div>';
			
			editor.popup(evt,html);

			JUtil.addEvent($ID('JEditorImageSubmit'),'click',JEditor.ImageButtonClick);
			
		}
	});

	this.toolbarList.push({
		name:'Url',
		tagName:"a",
		className:'url',
		value:'',
		title:'插入链接',
		onClick:function(evt,editor){
			evt = evt ? evt: ( window.event ? window.event :null );

			var sel = editor.selection;
			var range = editor.range;
			
			var lin = null;

			if(document.all) {
				if(sel.type == "Control" && range.length == 1) {	

					lin = editor.findParent("a", range);
				}
				if (sel.type == 'Text' || sel.type == 'None') {
					sel = editor.getSelection();
					range = editor.getRange(sel);
					lin = editor.findParent("a", range);
				}
			} else {
				lin = editor.findParent("a", range);
			}

			var href = '';
			if(lin != null) href = lin.href;
			else
				href = 'http://';

			var html = '<div class="insertLink">链接地址:<br/><input id="JEditorLink" value="' + href + '" /><br /><input id="sadfdsa" type="button" value="确定" onclick="JEditor.InsertLink(this);" /></div>';


			editor.popup(evt,html);
			
		}
	});


	this.toolbarList.push({
		name:'Color',
		tagName:"a",
		className:'color',
		value:'',
		title:'颜色',
		onClick:function(evt,editor){

			var COLORS = new Array(
				"#000000","#993300","#333300","#003300","#003366","#000080",
				"#333399","#333333","#800000","#FF6600","#808000","#008000",
				"#008080","#0000FF","#666699","#808080","#FF0000","#FF9900",
				"#99CC00","#339966","#33CCCC","#3366FF","#800080","#999999",
				"#FF00FF","#FFCC00","#FFFF00","#00FF00","#00CCFF","#993366",
				"#C0C0C0","#FF99CC","#FFCC99","#FFFF99","#CCFFCC","#CCFFFF",
				"#99CCFF","#666699","#777777","#999999","#EEEEEE","#FFFFFF"	
			);
			

			var html = '<table class="colorTable" onclick="JEditor.ColorClick(event);" border=0><tbody><tr>';

			for(var i = 0; i < COLORS.length;i++){
				var color = COLORS[i];
				html += '<td><div style="background-color: ' + color + ';"/></td>';

				if(i % 7 == 6) {
					html += "</tr><tr>";
				}
			}

			html += '</tbody></table>';	

			editor.popup(evt,html);
		}
	});


	this.toolbarList.push({
		name:'Size',
		tagName:"a",
		className:'size',
		value:'大小',
		title:'字体大小',
		onClick:function(evt,editor){
			var html = '<div class="sizeDiv" onclick="JEditor.FontSize(event);"><font size="1">1号字</font><font size="2">2号字</font><font size="3">3号字</font><font size="4">4号字</font><font size="5">5号字</font><font size="6">6号字</font><font size="7">7号字</font></div>';
			editor.popup(evt,html);
		}
	});
}


JEditor.JEditorHolder = new Array();

JEditor.closeAllPopup = function(evt){
	var len = JEditor.JEditorHolder.length;
	for(var i=0;i<len;i++){
		var ed = JEditor.JEditorHolder[i];
		if(ed.loaded){
			ed.closePopup(evt,true);
		}
	}
}


JEditor.GetPosition = function(e) {
	var left = 0;
	var top  = 0;
	while (e.offsetParent){
		left += e.offsetLeft;
		top  += e.offsetTop;
		e     = e.offsetParent;
	}
	left += e.offsetLeft;
	top  += e.offsetTop;
	return {x:left, y:top};
}


JEditor.ImageSelect = function(el){

	switch(el.id){
		case '_JEditorImageLocal':
			$ID('_JEditorImageLocal').style.backgroundColor = '#E8F3FD';
			$ID('_JEditorImageLocal').style.fontWeight = 'bold';
			$ID('JEditorImageLocal').style.display = 'block';
			$ID('_JEditorImageRemote').style.backgroundColor = '#FFFFFF';
			$ID('_JEditorImageRemote').style.fontWeight = 'normal';
			$ID('JEditorImageRemote').style.display = 'none';
			break;

		default:
			$ID('_JEditorImageLocal').style.backgroundColor = '#FFFFFF';
			$ID('_JEditorImageLocal').style.fontWeight = 'normal';
			$ID('JEditorImageLocal').style.display = 'none';
			$ID('_JEditorImageRemote').style.backgroundColor = '#E8F3FD';
			$ID('_JEditorImageRemote').style.fontWeight = 'bold';
			$ID('JEditorImageRemote').style.display = 'block';


	}

	return false;
}

JEditor.ColorClick = function(evt){
	var el = evt.srcElement;
	
	if(el != null && el.tagName.toLowerCase() == 'div'){
		var editor = JEditor.FindEditor(evt);
		editor.execCommand('ForeColor',el.style.backgroundColor);
		editor.closePopup(evt,true);

	}
}

JEditor.FontSize = function(evt){
	var el = evt.srcElement;
	
	if(el != null && el.tagName.toLowerCase() == 'font'){
		var editor = JEditor.FindEditor(evt);
		editor.execCommand('FontSize',el.size);
		editor.closePopup(evt,true);

	}

}

JEditor.ImageButtonClick = function(evt){
	var editor = JEditor.FindEditor(evt);

	if($ID('JEditorImageLocal').style.display != 'none'){
		editor.status = false;
		evt.srcElement.form.submit();
		return;
	}

	var el = evt.srcElement;

	evt = evt ? evt: ( window.event ? window.event :null );
	JEditor.InsertImage(evt,$ID('JEditorImageRemoteURL').value)

	
	editor.hidePopup(el);
}

JEditor.FindEditor = function(evt){
	var parent = evt.srcElement;
	while( parent != null){
		if(parent.getAttribute('editorIndex') != null){
			var editorIndex = parseInt(parent.getAttribute('editorIndex'));
			return JEditor.JEditorHolder[editorIndex];
		}
		parent = parent.parentNode;
	}
	return null;
}

JEditor.FindEditorByElement = function(element){
	var parent = element;
	while( parent != null){
		if(parent.getAttribute('editorIndex') != null){
			var editorIndex = parseInt(parent.getAttribute('editorIndex'));
			return JEditor.JEditorHolder[editorIndex];
		}
		parent = parent.parentNode;
	}
	return null;
}

JEditor.InsertImage = function(evt,url){
	var editor = JEditor.FindEditor(evt);
	editor.insertImage(url,0,0,'','');
}

JEditor.GetJEditor = function(index){
	return JEditor.JEditorHolder[index];
}



JEditor.InsertLink = function(el){
	
	var editor = JEditor.FindEditorByElement(el);
	
	if($ID('JEditorLink').value.length == 0){
		var tag = editor.getTag(editor.range);

		if(tag != null && tag.tagName == 'A'){
			editor.removeNode();
		}
		editor.hidePopup(el);
		return;
	}

	var sel = editor.selection;
	var range = editor.range;


	if(document.all)
		range.select();
	var lin = null;


	if(document.all && sel.type == "Control" && range.length == 1){
		range = editor.getTextRange(range(0));
		range.select();
	}



	var doc = editor.frameDocument;

	lin = editor.findParent("a", range);

	var update = (lin == null) ? false : true;
	if(!update) {
		lin = doc.createElement("a");
	}


	lin.setAttribute("href",$ID('JEditorLink').value);
	lin.setAttribute("target","_blank");
	

	if(update) {
		editor.hidePopup(el);
		return;
	}

	if (document.all) {
		range.select();
		var txt = range.htmlText;
		if(txt.length == 0 ){
			txt = lin.href;
		}
		lin.innerHTML = txt;
		range.pasteHTML(lin.outerHTML); 
	} else {
		var node = range.startContainer;
		var pos = range.startOffset;

		if(node.nodeType != 3) {
			node = node.childNodes[pos];
		}
		
		
		if(node.tagName)
			lin.appendChild(node);
		else{
			lin.innerHTML = sel;
			if(lin.innerHTML.length == 0){
				lin.innerHTML = lin.href;
			}
				
		}



		editor.insertNodeAtSelection(lin,editor.frameDocument);
	}

	editor.hidePopup(el);

}



function getJEditor(index){
	return JEditor.GetJEditor(index);
}


JEditor.prototype = {
	
	initialToolbar:function(){

		this.toolbar = document.createElement('div');
		this.toolbar.className = 'toolBar';

		for(var i = 0;i <this.toolbarList.length;i++){
			var btn = this.toolbarList[i];
			
			var tb = document.createElement(btn.tagName);
			tb.setAttribute('toolbarIndex',i);

			if(btn.value && btn.value.length > 0){
				tb.innerHTML = btn.value;
			}

			if(btn.title) tb.title = btn.title;
			tb.name = btn.name;
			tb.className = btn.className;
			if(btn.name) tb.href = btn.name;

			tb.onclick = function(evt){
				evt = evt ? evt: ( window.event ? window.event :null );

				if(evt == null) return false;

				var element = this.parentNode;
				var editorIndex = -1;

				while(element != null){
					if(element.getAttribute('editorIndex') != null){
						editorIndex = parseInt(element.getAttribute('editorIndex'));
						break;
					}
					element = element.parentNode;;
				}
				
				if(editorIndex != -1){
					var editor = JEditor.JEditorHolder[editorIndex];
					
					var toolbarIndex = parseInt(this.getAttribute('toolbarIndex'));

					editor.editorFrame.contentWindow.focus();
					var sel = editor.getSelection();
					if(sel.type == 'None'){
						editor.frameDocument.body.focus();
					}
					var range = editor.getRange(sel);

					

					editor.selection = sel;
					editor.range = range;
					
					
					
					try{
						var btn = editor.toolbarList[toolbarIndex];
						if(btn.onClick)
							btn.onClick(evt,editor);
					} catch(e){
						alert(e);
					}
				}

				return false;
			}

			

			this.toolbar.appendChild(tb);
		}

		this.container.insertBefore(this.toolbar,this.container.firstChild);
		
	},
	initialContainer:function(){
		this.container = document.createElement('div');
		this.container.style.width = this.width + 'px';
		this.container.style.position = 'relative';
		this.container.className = 'JEditor';
		this.container.setAttribute('editorIndex',this.index);
		this.target.insertAdjacentElement("afterEnd",this.container);
	},
	initialEditor:function(){
		
		this.editorFrame = document.createElement('iframe');
		
		this.editorFrame.style.height = this.height + 'px';
		this.editorFrame.style.width = this.width + 'px';

		this.editorFrame.className = 'editorFrame';
		this.editorFrame.style.overflow = 'auto';


		this.container.appendChild(this.editorFrame);

		this.frameDocument = this.editorFrame.contentWindow.document;

		
		this.frameDocument.open();

		if(this.value!=null){
			this.frameDocument.write(this.value);
		}else{
			this.frameDocument.write(this.target.value);
		}
		
		this.frameDocument.close();

		
		var link = this.frameDocument.createElement("link");
		link.setAttribute("rel", "stylesheet");
		link.setAttribute("type", "text/css");
		link.setAttribute("href", "doc.css");
		var heads = this.frameDocument.getElementsByTagName("head");
		for(var i=0;i < heads.length; i++) {
			heads[i].appendChild(link);
		}



		this.frameBody = this.frameDocument.body;
		this.frameBody.style.borderWidth = "0px";
		this.frameBody.style.margin = "0px";
		this.frameBody.style.height = "100%";
		this.frameBody.setAttribute('editorIndex',this.index);

		//set the body can be eidt
		this.frameBody.contentEditable ? this.frameBody.contentEditable = true : this.editorFrame.contentWindow.document.designMode="on";
		
	},
	initial:function(){
		this.target = $ID(this.targetId);
		
		if(this.target == null){
			alert('Please the element id named [' + this.targetId + ']');
			return false;
		}
		
		this.target.style.display = 'none';

		this.initialContainer();
		this.initialEditor();
		this.initialToolbar();

		this.loaded = true;

		var setValueHandle = function(evt){
			
			evt = evt ? evt: ( window.event ? window.event :null );
			if(evt == null) return;
			var editor = JEditor.FindEditor(evt);
			if(editor==null) return;

			editor.target.value = editor.getHTMLValue();
		};


		JUtil.addEvent(this.frameDocument.body,'click',JEditor.closeAllPopup);

		this.status = true;


		var fromHandle = function(evt){
			evt = evt ? evt: ( window.event ? window.event :null );
			if(evt == null) return;

			var form = evt.srcElement;

			if(form.tagName.toLowerCase() == 'form'){

				for(var i = 0 ; i < JEditor.JEditorHolder.length; i++){
					var editor = JEditor.JEditorHolder[i];
					if(form == editor.target.form){
						editor.target.value = editor.getValue();
					}
				}
			}
			
		}

		JUtil.addEvent(this.frameDocument.body,'click',JEditor.closeAllPopup);
		this.status = true;

		var fm = this.target.form;

		if(fm != null){
			JUtil.addEvent(fm,'submit',fromHandle);
		}


	},
	setEditable:function(val){
		if(this.container.frameBody.contentEditable){
			this.container.frameBody.contentEditable = val;
		} else {
			this.container.editorFrame.contentWindow.document.designMode = val ? "on" : "off";
		}
		

	},
	display:function(bl){
		if(bl){//display
			if(!this.loaded){
				this.initial();
			}
		}else{//hide
			if(this.loaded){
				this.value = this.getHTMLValue();
				this.container.parentNode.removeChild(this.container);
				this.loaded = false;
			}
		}

	},
	getSelection:function(){
		var sel = null;

		if(this.editorFrame.contentWindow.getSelection){
			sel = this.editorFrame.contentWindow.getSelection();
		}
		else if (this.frameDocument.getSelection) {
			
			sel = this.frameDocument.getSelection();
		}
		else if (this.frameDocument.selection) {
			sel = this.frameDocument.selection;
		}
		return sel;

	},
	getTextRange: function(element){
		var range = element.parentTextEdit.createTextRange();
		range.moveToElementText(element);
		return range;
	},
	execCommand:function(cmd,value){
		
		if(document.all) this.range.select();

		if(typeof(value) == "undefined") value = null;
		if(cmd == 'Italic' || cmd == 'Bold' || cmd == 'FormatBlock' || cmd == 'Underline' || cmd == 'Strikethrough' || cmd == 'FontName' || cmd == 'FontSize' || cmd == 'Justifyleft' || cmd == 'Justifycenter' || cmd == 'Justifyright' || cmd == 'InsertUnorderedList' || cmd == 'InsertOrderedList' || cmd == 'Outdent' || cmd == 'Indent' || cmd == 'ForeColor' ){
			this.frameDocument.execCommand(cmd, false, value);
			return;
		}

	},
	setValue:function(val){
		this.value = val;
		if(this.loaded){
			this.frameBody.innerHTML = val;
		}
	},
	insertImage:function(src,width,height,align,alt){
		var sel = this.selection;
		var range = this.range;

		var img = this.findParent("img", range);

		var update = (img == null) ? false : true;

		if(!update) {
			img = this.frameDocument.createElement("img");
		}

		img.setAttribute('src',src);
		img.setAttribute('border',0);

		if(width > 0)
			img.style.width = width + 'px';

		if(height > 0)
			img.style.height = height + 'px';

		if(alt != '')
			img.setAttribute('alt',alt);

		if(align != "") { img.setAttribute("align", align); } else { img.removeAttribute("align"); }

		img.removeAttribute("width");
		img.removeAttribute("height");

		if(update) { return; }
		
		if (document.all) {
			range.pasteHTML(img.outerHTML);   
		}
		else {
			this.insertNodeAtSelection(img, this.frameDocument);
		}
		this.closePopup();
	},
	popup:function(evt,html){
		
		if(this.popupWin == null){
			this.popupWin = document.createElement('div');
			this.popupWin.style.border = '1px solid #9DB3C5';
			this.popupWin.style.padding = '5px';
			this.popupWin.style.position = 'absolute';
			this.popupWin.className = 'JEditorPopup';
			document.body.appendChild(this.popupWin);
			this.popupWin.setAttribute('editorIndex',this.index);
		}else{
			this.popupWin.innerHTML = '';
		}

		

		this.popupBar = evt.srcElement;
		this.popupWin.style.display = 'block';
		var btn = evt.srcElement;

		var btnPosition = JEditor.GetPosition(btn);

		this.popupWin.style.left = btnPosition.x + 'px';
		this.popupWin.style.top = (btnPosition.y + btn.offsetHeight) + 'px';

		this.popupWin.innerHTML = html;


	},
	hidePopup:function(srcElement){

		if(this.popupWin != null){
			var len = this.popupWin.childNodes.length;
			if(this.popupWin.childNodes.length > 0){
				for(var i=0;i<len;i++){
					this.popupWin.removeChild(this.popupWin.childNodes[i]);
				}
			}
			this.popupWin.style.display = 'none';

			return;
		}
	},

	closePopup:function(evt,overClose){
		if(evt == null){
			this.popupWin.style.display = 'none';
			return;
		}
		if(overClose && this.popupWin != null){
			var len = this.popupWin.childNodes.length;
			if(this.popupWin.childNodes.length > 0){
				for(var i=0;i<len;i++){
					this.popupWin.removeChild(this.popupWin.childNodes[i]);
				}
			}
			this.popupWin.style.display = 'none';
			return;
		}

		var close = true;
		
		if(evt.srcElement.getAttribute('toolbarindex') != null){
			if(this.popupBar == evt.srcElement)
			close = false;
		}

		var parent = evt.srcElement;

		while( parent != null){
			if(parent == this.popupWin){//click on popup
				close = false;
				break;
			}
			parent = parent.parentNode;
		}

		if(this.popupWin != null && close){
			var len = this.popupWin.childNodes.length;
			if(this.popupWin.childNodes.length > 0){
				for(var i=0;i<len;i++){
					this.popupWin.removeChild(this.popupWin.childNodes[i]);
				}
			}
			this.popupWin.style.display = 'none';
		}

	},
	getRange: function(sel) {
		return sel.createRange ? sel.createRange() : sel.getRangeAt(0);
	},
	findParent:function(parentTagName, range){
		parentTagName = parentTagName.toUpperCase();
		var rangeWorking;
		var elmWorking = null;
		
		try {
			if(!document.all) {
				var node = range.startContainer;	
				var pos = range.startOffset;
				if(node.nodeType != 3) { node = node.childNodes[pos]; }
				return this.findParentNode(parentTagName, node);
			}
			else {
				elmWorking = (range.length > 0) ? range.item(0): range.parentElement();	
				
				elmWorking = this.findParentNode(parentTagName, elmWorking);
				
				if(elmWorking != null) return elmWorking;

				rangeWorking = range.duplicate();
				rangeWorking.collapse(true);
				rangeWorking.moveEnd("character", 1);
				if (rangeWorking.text.length>0) {
					
					while (rangeWorking.compareEndPoints("EndToEnd", range) < 0){
			  			rangeWorking.move("Character");
			  			if (null != this.findParent(parentTagName, rangeWorking)){
			   				return this.findParent(parentTagName, rangeWorking);
			  			}
			 		}
			 	}
				
			 	return null;
			}
		}
		catch(e) {
			return null;
		}
	},
	findParentNode: function(tagName, node) {
		while (node.tagName != "HTML") {
	  		if (node.tagName == tagName){
	  			return node;
	  		} 
	  		node = node.parentNode;
	 	}
	 	return null;
	},
	insertNodeAtSelection: function(insertNode, doc) {
		
		var sel = this.getSelection();
		
		var range = sel.getRangeAt(0);
		
		sel.removeAllRanges();
		
		range.deleteContents();
		
		var container = range.startContainer;
		var pos = range.startOffset;
		
		range = doc.createRange();
		
		if (container.nodeType==3 && insertNode.nodeType==3) {					
			container.insertData(pos, insertNode.data);
			range.setEnd(container, pos+insertNode.length);
			range.setStart(container, pos+insertNode.length);		
		} 	
		else {
		
			var afterNode;	
			var beforeNode;
			if (container.nodeType==3) {
				var textNode = container;
				container = textNode.parentNode;
				var text = textNode.nodeValue;
				
				var textBefore = text.substr(0,pos);
				var textAfter = text.substr(pos);
				
				beforeNode = document.createTextNode(textBefore);
				afterNode = document.createTextNode(textAfter);
				
				container.insertBefore(afterNode, textNode);
				container.insertBefore(insertNode, afterNode);
				container.insertBefore(beforeNode, insertNode);
				
				container.removeChild(textNode);
			} 
			else {
				afterNode = container.childNodes[pos];
				container.insertBefore(insertNode, afterNode);
			}
			
			try {
				range.setEnd(afterNode, 0);
				range.setStart(afterNode, 0);
			}
			catch(e) {
			}
		}
		
		sel.addRange(range);
	},
	getIframe:function(){
		if(this.iframe == null){
			var frameName = 'jeditorIframe' + this.index;

			if(document.all)
				this.iframe = document.createElement('<iframe name="' + frameName + '"></iframe>');
			else
				this.iframe = document.createElement('iframe');
			

			this.iframe.name = frameName;
			this.iframe.style.display = 'none';
			
			this.container.appendChild(this.iframe);

			
		}
		return this.iframe;
	},
	getTag: function(range) {
		try {
		    if(!document.all) {
				var node = range.startContainer;	
				var pos = range.startOffset;
				if(node.nodeType != 3) { node = node.childNodes[pos]; }
				
				if(node.nodeName && node.nodeName.search(/#/) != -1) {
					return node.parentNode;
				}
				return node;
			}
			else {
				if(range.length > 0) {
					return range.item(0);
				}
				else if(range.parentElement()) {
					return range.parentElement();
				}
			}
			return null;
		}
		catch(e) {
			return null;
		}
	},
	removeNode: function() {

		var sel = this.selection;
		var range = this.range;

		var tag = this.getTag(range);

		var parent = tag.parentNode;
		if(tag == null || parent == null) { return; }
		if(tag.nodeName == "HTML" || tag.nodeName == "BODY") { return; }

		var childNodes = new Array();
		for(var i=0; i < tag.childNodes.length;i++)
			childNodes[i] = tag.childNodes[i];	
		for(var i=0; i < childNodes.length;i++)
			parent.insertBefore(childNodes[i], tag);	
		

		parent.removeChild(tag);

		if(parent.nodeName == "A" && !parent.hasChildNodes()) {
			if(parent.parentNode) { parent.parentNode.removeChild(parent);}
		}

	},
	getValue:function(){
		if(!this.loaded) return null;
		return this.getHTMLValue();
	},
	getHTMLValue:function(){
		var content = this.frameDocument.body.innerHTML;
		return content;
	},
	insertText:function(txt){
		this.insertHTML(HtmlEncode(txt));
	},
	insertHTML:function(html){

		if (document.all) {
			this.frameDocument.body.focus();
			this.getSelection().createRange().pasteHTML(html);   
		} 
		else {
			var span = this.frameDocument.createElement("span");
			
			this.insertNodeAtSelection(span,this.frameDocument);
			span.innerHTML = html;
		}
		
	}

}
